"""
  Copyright 2008 Texas A&M University Licensed under the
  Educational Community License, Version 2.0 (the "License"); you may
  not use this file except in compliance with the License. You may
  obtain a copy of the License at
  
  http://www.osedu.org/licenses/ECL-2.0

  Unless required by applicable law or agreed to in writing,
  software distributed under the License is distributed on an "AS IS"
  BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
  or implied. See the License for the specific language governing
  permissions and limitations under the License.
"""

import time
from lxml import etree

from meercat.server.oai import constants

nsmap = {None: 'http://www.openarchives.org/OAI/2.0/',
         'xsi': 'http://www.w3.org/2001/XMLSchema-instance',}

def OAIPMH():
    a = {'{%s}schemaLocation' % (nsmap['xsi'],): 
             'http://www.openarchives.org/OAI/2.0/ ' \
             'http://www.openarchives.org/OAI/2.0/OAI-PMH.xsd'}
    
    return etree.Element("OAI-PMH",attrib=a,nsmap=nsmap)

def Error(code, freetext=u'', tag=u'error'):
    if not code in constants.error_codes:
        raise ValueError('OAIError code must be in: '
                         '%s' % (', '.join(constants.error_codes)))
    
    t = etree.Element(tag, attrib={u'code': code})
    
    if freetext:
        t.text = freetext
    
    return t

def ResponseDate(tag=u'responseDate'):
    t = etree.Element(tag)
    t.text = time.strftime(constants.datetime_format, time.gmtime())
    
    return t

def Request(request, tag=u'request'):
    t = etree.Element(tag)
    t.text = 'http://%s:%s%s' % (request.getHost().host, request.getHost().port,
                                 request.path)
    
    return t

def ResumptionToken(token, tag=u'resumptionToken',expirationDate=None,
                    completeListSize=None,cursor=None):
    t = etree.Element(tag)
    t.text = token
    if expirationDate is not None:
        t.set('expirationDate',expirationDate)
    if completeListSize is not None:
        t.set('completeListSize',str(completeListSize))
    if cursor is not None:
        t.set('cursor',str(cursor))
    
    return t

def MetadataFormat(metadataPrefix, schema, metadataNamespace,
                   tag=u'metadataFormat'):
    f = etree.Element(tag)
    t = etree.Element(u'metadataPrefix')
    t.text = metadataPrefix
    f.append(t)
    t = etree.Element(u'schema')
    t.text = schema
    f.append(t)
    t = etree.Element(u'metadataNamespace')
    t.text = metadataNamespace
    f.append(t)
    return f